<template>
    <PageLayout 
        title="智能干支图示" 
        show-back 
        @back="goBack" 
        fixed 
        shadow 
        :content-padding="false"
        :tabs="tabs"
        :scrollable="false"
        v-model="activeTab"
        @tab-change="handleTabChange"
    >
        <!-- 干支 tab -->
        <template #tab-ganzhi>
            <div class="bazi-relations">
                <div class="relation-content">
                    <div v-if="resultData && relationPillars.length >= 4" class="relation-section-container">
                        <GanzhiRelations :pillars="relationPillars" />
                    </div>
                </div>
            </div>
        </template>

        <!-- 流通 tab -->
        <template #tab-circulation>
            <div class="bazi-relations">
                <div class="relation-content">
                    <div v-if="resultData && circulationPillars.length >= 4" class="relation-section-container">
                        <Circulation :pillars="circulationPillars" />
                    </div>
                </div>
            </div>
        </template>

        <!-- 宫位 tab -->
        <template #tab-palace>
            <div class="bazi-relations">
                <div class="relation-content">
                    <div v-if="resultData && basePillars.length >= 4" class="relation-section-container">
                        <Palace :pillars="basePillars" />
                    </div>
                </div>
            </div>
        </template>

        <!-- 六亲 tab -->
        <template #tab-relation>
            <div class="bazi-relations">
                <div class="relation-content">
                    <!-- 关系显示（内部包含 tab 切换） -->
                    <div v-if="resultData && basePillars.length >= 4" class="relation-section-container">
                        <RelationDisplay :pillars="basePillars" :gender="resultData?.baseInfo?.genderTraditional || '男'" />
                    </div>
                </div>
            </div>
        </template>
    </PageLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { baziApi } from '@/api/bazi'
import PageLayout from '@/components/PageLayout.vue'
import GanzhiRelations from '@/components/GanzhiRelations.vue'
import Circulation from '@/components/Circulation.vue'
import Palace from '@/components/Palace.vue'
import RelationDisplay from '@/components/relation_display.vue'

const router = useRouter()
const route = useRoute()
const resultData = ref<any>(null)
const activeTab = ref<string | number>('ganzhi')

// 定义四个主选项卡
const tabs = [
    { label: '干支', value: 'ganzhi' },
    { label: '流通', value: 'circulation' },
    { label: '宫位', value: 'palace' },
    { label: '六亲', value: 'relation' }
]

// 返回上一页
const goBack = () => {
    router.back()
}

// Tab 切换处理
const handleTabChange = (value: string | number) => {
    activeTab.value = value
}

// 时间数据
const timeData = ref<any>({
    decade: null,
    fortune: null,
    month: null,
    day: null,
    hour: null
})

// 加载时间数据（如果来自专业细盘）
const loadTimeData = async () => {
    const fromDetail = route.query.fromDetail === 'true'
    if (!fromDetail) return
    
    try {
        const params: any = {
            datetime: route.query.datetime as string,
            gender: (parseInt(route.query.gender as string) || 1) as 0 | 1,
            enableZiShiSupport: route.query.enableZiShiSupport === 'true'
        }
        
        // 加载大运数据
        if (route.query.decadeIndex !== undefined) {
            const decadeIndex = parseInt(route.query.decadeIndex as string)
            const decadeResponse = await baziApi.getDecadeList(params)
            const decadeList = (decadeResponse.data?.data || decadeResponse.data || []) as any[]
            if (decadeList[decadeIndex]) {
                timeData.value.decade = decadeList[decadeIndex]
                
                // 加载流年数据
                if (route.query.fortuneIndex !== undefined && decadeList[decadeIndex].children) {
                    const fortuneIndex = parseInt(route.query.fortuneIndex as string)
                    const fortuneList = decadeList[decadeIndex].children as any[]
                    if (fortuneList[fortuneIndex]) {
                        timeData.value.fortune = fortuneList[fortuneIndex]
                        
                        // 加载流月数据
                        if (route.query.monthIndex !== undefined) {
                            const monthIndex = parseInt(route.query.monthIndex as string)
                            const monthResponse = await baziApi.getMonthList({
                                ...params,
                                decadeIndex,
                                fortuneIndex
                            })
                            const monthList = (monthResponse.data?.data || monthResponse.data || []) as any[]
                            if (monthList[monthIndex]) {
                                timeData.value.month = monthList[monthIndex]
                                
                                // 加载流日数据
                                if (route.query.dayIndex !== undefined) {
                                    const dayIndex = parseInt(route.query.dayIndex as string)
                                    const dayResponse = await baziApi.getDayList({
                                        ...params,
                                        decadeIndex,
                                        fortuneIndex,
                                        monthIndex
                                    })
                                    const dayList = (dayResponse.data?.data || dayResponse.data || []) as any[]
                                    if (dayList[dayIndex]) {
                                        timeData.value.day = dayList[dayIndex]
                                        
                                        // 加载流时数据
                                        if (route.query.hourIndex !== undefined) {
                                            const hourIndex = parseInt(route.query.hourIndex as string)
                                            const hourResponse = await baziApi.getHourList({
                                                ...params,
                                                decadeIndex,
                                                fortuneIndex,
                                                monthIndex,
                                                dayIndex
                                            })
                                            const hourList = (hourResponse.data?.data || hourResponse.data || []) as any[]
                                            if (hourList[hourIndex]) {
                                                timeData.value.hour = hourList[hourIndex]
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (error) {
        console.error('加载时间数据失败:', error)
    }
}

// 从干支中提取天干
const extractStem = (item: any): string => {
    if (item.stem) return item.stem
    if (item.ganzhi && item.ganzhi.length >= 1) return item.ganzhi[0]
    return ''
}

// 从干支中提取地支
const extractBranch = (item: any): string => {
    if (item.branch) return item.branch
    if (item.ganzhi && item.ganzhi.length >= 2) return item.ganzhi[1]
    return ''
}

// 获取地支十神（从藏干中获取第一个）
const getZhiLabel = (zanggan: any[]): string => {
    if (!zanggan || zanggan.length === 0) return ''
    return zanggan[0]?.tenStar || ''
}

// 构建基础四柱数据（只包含年、月、日、时，用于宫位和六亲 tab）
const basePillars = computed(() => {
    if (!resultData.value) return []
    const pillars = []
    
    // 基础四柱
    if (resultData.value.year?.stem && resultData.value.year?.branch) {
        pillars.push({
            gan: resultData.value.year.stem,
            zhi: resultData.value.year.branch,
            label: '年柱',
            zhiLabel: getZhiLabel(resultData.value.year?.zanggan),
            tenStar: resultData.value.year?.tenStar || ''
        })
    }
    
    if (resultData.value.month?.stem && resultData.value.month?.branch) {
        pillars.push({
            gan: resultData.value.month.stem,
            zhi: resultData.value.month.branch,
            label: '月柱',
            zhiLabel: getZhiLabel(resultData.value.month?.zanggan),
            tenStar: resultData.value.month?.tenStar || ''
        })
    }
    
    if (resultData.value.day?.stem && resultData.value.day?.branch) {
        pillars.push({
            gan: resultData.value.day.stem,
            zhi: resultData.value.day.branch,
            label: '日柱',
            zhiLabel: getZhiLabel(resultData.value.day?.zanggan),
            tenStar: resultData.value.day?.tenStar || ''
        })
    }
    
    if (resultData.value.hour?.stem && resultData.value.hour?.branch) {
        pillars.push({
            gan: resultData.value.hour.stem,
            zhi: resultData.value.hour.branch,
            label: '时柱',
            zhiLabel: getZhiLabel(resultData.value.hour?.zanggan),
            tenStar: resultData.value.hour?.tenStar || ''
        })
    }
    
    return pillars
})

// 构建关系组件所需的天干地支数据（包含时间数据，用于干支和流通 tab）
const relationPillars = computed(() => {
    if (!resultData.value) return []
    const pillars = []
    
    // 添加时间数据（如果存在）
    const fromDetail = route.query.fromDetail === 'true'
    
    // 流时
    if (fromDetail && timeData.value.hour) {
        const item = timeData.value.hour
        const stem = extractStem(item)
        const branch = extractBranch(item)
        if (stem && branch) {
            pillars.push({
                gan: stem,
                zhi: branch,
                label: '流时',
                zhiLabel: getZhiLabel(item?.zanggan || []),
                tenStar: item?.tenStar?.heavenStem || item?.tenStar?.heavenStemShort || ''
            })
        }
    }
    
    // 流日
    if (fromDetail && timeData.value.day) {
        const item = timeData.value.day
        const stem = extractStem(item)
        const branch = extractBranch(item)
        if (stem && branch) {
            pillars.push({
                gan: stem,
                zhi: branch,
                label: '流日',
                zhiLabel: getZhiLabel(item?.zanggan || []),
                tenStar: item?.tenStar?.heavenStem || item?.tenStar?.heavenStemShort || ''
            })
        }
    }
    
    // 流月
    if (fromDetail && timeData.value.month) {
        const item = timeData.value.month
        const stem = extractStem(item)
        const branch = extractBranch(item)
        if (stem && branch) {
            pillars.push({
                gan: stem,
                zhi: branch,
                label: '流月',
                zhiLabel: getZhiLabel(item?.zanggan || []),
                tenStar: item?.tenStar?.heavenStem || item?.tenStar?.heavenStemShort || ''
            })
        }
    }
    
    // 流年
    if (fromDetail && timeData.value.fortune) {
        const item = timeData.value.fortune
        const stem = extractStem(item)
        const branch = extractBranch(item)
        if (stem && branch) {
            pillars.push({
                gan: stem,
                zhi: branch,
                label: '流年',
                zhiLabel: getZhiLabel(item?.zanggan || []),
                tenStar: item?.tenStar?.heavenStem || item?.tenStar?.heavenStemShort || ''
            })
        }
    }
    
    // 大运（或小运）
    if (fromDetail && timeData.value.decade) {
        const item = timeData.value.decade
        const stem = extractStem(item)
        const branch = extractBranch(item)
        if (stem && branch) {
            const label = item.xiaoyun ? '小运' : '大运'
            pillars.push({
                gan: stem,
                zhi: branch,
                label: label,
                zhiLabel: getZhiLabel(item?.zanggan || []),
                tenStar: item?.tenStar?.heavenStem || item?.tenStar?.heavenStemShort || ''
            })
        }
    }
    
    // 添加基础四柱
    pillars.push(...basePillars.value)
    
    return pillars
})

// 构建流通组件所需的天干地支数据（包含十神标签）
const circulationPillars = computed(() => {
    if (!resultData.value) return []
    const pillars = []
    
    // 获取地支十神（从藏干中获取第一个，或使用其他逻辑）
    const getZhiLabel = (zanggan: any[]): string => {
        if (!zanggan || zanggan.length === 0) return ''
        // 取第一个藏干的十神作为地支标签
        return zanggan[0]?.tenStar || ''
    }
    
    if (resultData.value.year?.stem && resultData.value.year?.branch) {
        pillars.push({
            gan: resultData.value.year.stem,
            zhi: resultData.value.year.branch,
            label: '年柱',
            ganLabel: resultData.value.year?.tenStar || '',
            zhiLabel: getZhiLabel(resultData.value.year?.zanggan)
        })
    }
    
    if (resultData.value.month?.stem && resultData.value.month?.branch) {
        pillars.push({
            gan: resultData.value.month.stem,
            zhi: resultData.value.month.branch,
            label: '月柱',
            ganLabel: resultData.value.month?.tenStar || '',
            zhiLabel: getZhiLabel(resultData.value.month?.zanggan)
        })
    }
    
    if (resultData.value.day?.stem && resultData.value.day?.branch) {
        pillars.push({
            gan: resultData.value.day.stem,
            zhi: resultData.value.day.branch,
            label: '日柱',
            ganLabel: resultData.value.day?.tenStar || '日主',
            zhiLabel: getZhiLabel(resultData.value.day?.zanggan)
        })
    }
    
    if (resultData.value.hour?.stem && resultData.value.hour?.branch) {
        pillars.push({
            gan: resultData.value.hour.stem,
            zhi: resultData.value.hour.branch,
            label: '时柱',
            ganLabel: resultData.value.hour?.tenStar || '',
            zhiLabel: getZhiLabel(resultData.value.hour?.zanggan)
        })
    }
    
    return pillars
})

// 获取排盘结果
const getBaziResult = async () => {
    try {
        // 从路由参数获取排盘参数
        const params = route.query
        if (params.datetime) {
            const response = await baziApi.getBaziInfo({
                datetime: params.datetime as string,
                gender: (parseInt(params.gender as string) || 1) as 0 | 1,
                name: params.name as string || '',
                longitude: params.longitude ? parseFloat(params.longitude as string) : undefined,
                latitude: params.latitude ? parseFloat(params.latitude as string) : undefined,
                enableZiShiSupport: params.enableZiShiSupport === 'true'
            })
            resultData.value = response.data
        } else {
            // 如果没有参数，尝试从localStorage获取
            const data = localStorage.getItem('baziResult')
            if (data) {
                resultData.value = JSON.parse(data)
            } else {
                router.push('/')
            }
        }
    } catch (error) {
        console.error('获取排盘结果失败:', error)
        router.push('/')
    }
}

// 组件挂载时获取数据
onMounted(async () => {
    await getBaziResult()
    await loadTimeData()
})
</script>

<style scoped>
.bazi-relations {
    height: 100%;
    background: #ffffff;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.relation-content {
    width: 100%;
    max-width: 100%;
    box-sizing: border-box;
    padding: 0;
    overflow: hidden;
    flex: 1;
    /* 占据剩余空间 */
    display: flex;
    flex-direction: column;
}

.relation-section-container {
    margin: 16px;
    padding: 0;
    width: calc(100% - 32px);
    max-width: 100%;
    box-sizing: border-box;
    overflow: hidden;
    flex: 1;
    /* 占据剩余空间 */
    display: flex;
    flex-direction: column;
}
</style>

